import config from "@/config";
import storage from "@/utils/storage";
import constant from "@/utils/constant";
import { login, logout, getInfo, removeBinding } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { isPhoneNumber } from "@/utils/tools";

const baseUrl = config.baseUrl;

const user = {
  state: {
    token: getToken(),
    openid: storage.get(constant.openid),
    phone: storage.get(constant.phone),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    // 部门
    dept: storage.get(constant.dept),
    // 登录时间
    loginDate: storage.get(constant.loginDate),
    nickName: storage.get(constant.nickName),
    // 用户openid，用于判断是否关注公主号
    userOpenid: !storage.get(constant.userOpenid),
    isFirstLogin: storage.get(constant.isFirstLogin),
    userId: storage.get(constant.userId),
    userName: storage.get(constant.userName),
    routerList: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USERID: (state, userId) => {
      state.userId = userId;
    },
    SET_USERNAME: (state, userName) => {
      state.userName = userName;
    },
    SET_ISFIRSTLOGIN: (state, isFirstLogin) => {
      state.isFirstLogin = isFirstLogin;
    },
    SET_OPENID: (state, openid) => {
      state.openid = openid;
      storage.set(constant.openid, openid);
    },
    SET_PHONE: (state, phone) => {
      state.phone = phone;
      storage.set(constant.phone, phone);
    },
    SET_NAME: (state, name) => {
      state.name = name;
      storage.set(constant.name, name);
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
      storage.set(constant.avatar, avatar);
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
      storage.set(constant.roles, roles);
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
      storage.set(constant.permissions, permissions);
    },
    SET_DEPT: (state, dept) => {
      state.dept = dept;
      storage.set(constant.dept, dept);
    },
    SET_NICKNAME: (state, nickName) => {
      state.nickName = nickName;
      storage.set(constant.nickName, nickName);
    },
    SET_LOGINDATE: (state, loginDate) => {
      state.loginDate = loginDate;
      storage.set(constant.loginDate, loginDate);
    },
    SET_USEROPENID: (state, userOpenid) => {
      state.userOpenid = userOpenid;
      storage.set(constant.userOpenid, userOpenid);
    },
    SET_ROUTRRLIST: (state, routerList) => {
      state.routerList = routerList;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const xcxOpenId = userInfo.xcxOpenId;
      const phone = userInfo.phone;
      return new Promise((resolve, reject) => {
        login({ username, password, xcxOpenId, phone })
          .then((res) => {
            if (res?.data?.status) {
              let isPhoneFlag = false;
              if (isPhoneNumber(userInfo.username)) {
                isPhoneFlag = true;
              }
              const userId = res.data.sysUser.userId; // 用户id
              const userName = isPhoneFlag
                ? res.data.sysUser.phonenumber
                : res.data.sysUser.userName; // 用户名
              uni.setStorageSync("firstLogin", res.data.token);
              // return false;
            }

            setToken(res.data.token);
            commit("SET_TOKEN", res.data.token);
            commit("SET_ISFIRSTLOGIN", res?.data?.status || "");
            commit("SET_USERID", res?.data?.sysUser?.userId || "");
            commit("SET_USERNAME", res?.data?.sysUser?.userName || "");

            // if (res?.data?.status) {
            //   uni.navigateTo({
            //     url: `/pages/forceResetPwd?userId=${userId}&userName=${userName}`,
            //   });
            // }
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(({ data: res }) => {
            const user = res.user;
            // 设置用户头像或者取默认头像
            const avatar =
              user == null || user.avatar == "" || user.avatar == null
                ? "https://glm-1324073348.cos.ap-nanjing.myqcloud.com/static/92ef36e470a64e61a9dd63d46a3a423b1710988427344.png"
                : user.avatar;
            const username =
              user == null || user.userName == "" || user.userName == null
                ? ""
                : user.userName;
            const dept = user == null || user.dept == null ? {} : user.dept;
            const nickName =
              user == null || user.nickName == null ? "" : user.nickName;
            const loginDate =
              user == null || user.loginDate == "" || user.loginDate == null
                ? ""
                : user.loginDate;
            const userOpenid =
              user == null || user.openId == "" || user.openId == null
                ? ""
                : user.openId;
            // 保存用户角色、权限控制
            if (res.roles && res.roles.length > 0) {
              commit("SET_ROLES", res.roles);
              commit("SET_PERMISSIONS", res.permissions);
            } else {
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            commit("SET_NAME", username);
            commit("SET_AVATAR", avatar);
            commit("SET_DEPT", dept);
            commit("SET_NICKNAME", nickName);
            commit("SET_LOGINDATE", loginDate);
            commit("SET_USEROPENID", userOpenid);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 解绑账号
    RemoveBinding({ commit, state }) {
      return new Promise((resolve, reject) => {
        removeBinding(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            storage.clean();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            storage.clean();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};

export default user;
